package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

/**
 * 
 * @author huangcd
 * 
 * @param <T>
 */
@SuppressWarnings("unchecked")
public class ObjectPersistence<T>
{
    public ObjectPersistence()
    {
    }

    public void save(T instance, OutputStream out) throws IOException
    {
        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(instance);
        oos.flush();
        oos.close();
    }

    public void save(T instance, File outFile) throws IOException
    {
        save(instance, new FileOutputStream(outFile));
    }

    public T load(InputStream in) throws IOException, ClassNotFoundException
    {
        ObjectInputStream ois = new ObjectInputStream(in);
        T instance = (T) ois.readObject();
        return instance;
    }

    public T load(File inFile) throws FileNotFoundException, IOException,
            ClassNotFoundException
    {
        return load(new FileInputStream(inFile));
    }
}
